<template>
  <div>
    <el-form ref="form" :model="preRegisterForm" :rules="rules" label-width="100px">
      <el-divider content-position="left">主申请人信息</el-divider>
      <el-form-item label="姓名" prop="mainRenter.name">
        <el-input v-model="preRegisterForm.mainRenter.name" placeholder="请输入申请人姓名" />
      </el-form-item>
      <el-form-item label="手机号" prop="mainRenter.contacts">
        <el-input v-model="preRegisterForm.mainRenter.contacts" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="身份证号" prop="mainRenter.idCardNumber">
        <el-input v-model="preRegisterForm.mainRenter.idCardNumber" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="房客类型" prop="mainRenter.renterType">
        <el-radio-group v-model="preRegisterForm.mainRenter.renterType">
          <el-radio label="1">省内房客</el-radio>
          <el-radio label="2">省外房客</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="证件照片" prop="mainRenter.picUrl">
        <el-upload
          class="avatar-uploader"
          action="/prod-api/common/upload"
          :headers="headers"
          :show-file-list="false"
          :on-success="(res) => handleUploadSuccess(res, 'main')"
          :before-upload="beforeUpload">
          <img v-if="preRegisterForm.mainRenter.picUrl" :src="preRegisterForm.mainRenter.picUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div class="el-upload__tip">请上传身份证照片，支持jpg/png格式，不超过2MB</div>
      </el-form-item>
      
      <el-divider content-position="left">
        同住人信息
        <el-button type="text" @click="addCohabitant" icon="el-icon-plus">添加同住人</el-button>
      </el-divider>
      
      <div v-for="(cohabitant, index) in preRegisterForm.cohabitants" :key="index" class="cohabitant-item">
        <el-divider>同住人 {{ index + 1 }}</el-divider>
        <el-row type="flex" justify="end">
          <el-button type="danger" size="mini" circle @click="removeCohabitant(index)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </el-row>
        <el-form-item :label="'姓名'" :prop="'cohabitants.' + index + '.name'" :rules="rules.cohabitantName">
          <el-input v-model="cohabitant.name" placeholder="请输入同住人姓名"></el-input>
        </el-form-item>
        <el-form-item :label="'手机号'" :prop="'cohabitants.' + index + '.contacts'" :rules="rules.cohabitantPhone">
          <el-input v-model="cohabitant.contacts" placeholder="请输入同住人手机号"></el-input>
        </el-form-item>
        <el-form-item :label="'身份证号'" :prop="'cohabitants.' + index + '.idCardNumber'" :rules="rules.cohabitantIdCard">
          <el-input v-model="cohabitant.idCardNumber" placeholder="请输入同住人身份证号"></el-input>
        </el-form-item>
        <el-form-item :label="'房客类型'" :prop="'cohabitants.' + index + '.renterType'" :rules="rules.cohabitantRenterType">
          <el-radio-group v-model="cohabitant.renterType">
            <el-radio label="1">省内房客</el-radio>
            <el-radio label="2">省外房客</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="'证件照片'">
          <el-upload
            class="avatar-uploader"
            action="/prod-api/common/upload"
            :headers="headers"
            :show-file-list="false"
            :on-success="(res) => handleUploadSuccess(res, index)"
            :before-upload="beforeUpload">
            <img v-if="cohabitant.picUrl" :src="cohabitant.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="el-upload__tip">请上传身份证照片，支持jpg/png格式，不超过2MB</div>
        </el-form-item>
      </div>
      
      <!-- 添加选择房间部分 -->
      <el-divider content-position="left">房间信息（可选）</el-divider>
      <el-form-item label="选择房间" prop="roomId">
        <el-input
            v-model="roomSearchName"
            placeholder="可搜索房间号"
            clearable
            style="margin-bottom: 10px;">
          <template #append>
            <el-button @click="handleSearchRoom">
              <el-icon><Search/></el-icon>
            </el-button>
          </template>
        </el-input>
        
        <el-select v-model="preRegisterForm.roomId" filterable placeholder="请选择房间（可选）" style="width: 100%;" clearable>
          <el-option
              v-for="item in roomList"
              :key="item.id || item.roomId"
              :label="`${item.name} - ${item.buildingName || ''}`"
              :value="item.id || item.roomId">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-divider content-position="left">其他信息</el-divider>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="preRegisterForm.remark" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { listAvailableRooms } from "@/api/room/room";
import { Search } from '@element-plus/icons-vue';

export default {
  name: "PreRegisterForm",
  components: {
    Search
  },
  props: {
    preRegisterId: {
      type: [Number, String],
      default: null
    },
    // 如果有已有数据传入则用于编辑
    initialData: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      // 上传文件头部参数
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 记录原始数据，用于取消操作时恢复
      originalData: null,
      // 表单数据
      preRegisterForm: {
        registerId: null,
        mainRenter: {
          name: '',
          contacts: '',
          idCardNumber: '',
          picUrl: '',
          mainFlag: '1', // 标记为主申请人
          renterType: '1' // 默认省内房客
        },
        cohabitants: [], // 同住人列表
        remark: '',
        roomId: null // 添加房间ID字段
      },
      // 表单校验规则
      rules: {
        'mainRenter.name': [
          { required: true, message: "申请人姓名不能为空", trigger: "blur" }
        ],
        'mainRenter.contacts': [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        'mainRenter.idCardNumber': [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: "请输入正确的身份证号码", trigger: "blur" }
        ],
        'mainRenter.renterType': [
          { required: true, message: "房客类型不能为空", trigger: "change" }
        ],
        cohabitantName: [
          { required: true, message: "同住人姓名不能为空", trigger: "blur" }
        ],
        cohabitantPhone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        cohabitantIdCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: "请输入正确的身份证号码", trigger: "blur" }
        ],
        cohabitantRenterType: [
          { required: true, message: "房客类型不能为空", trigger: "change" }
        ]
      },
      // 房间搜索相关
      roomSearchName: '',
      roomList: [],
      roomQueryParams: {
        pageNum: 1,
        pageSize: 50,
        name: ''
      }
    };
  },
  created() {
    // 如果传入了初始数据，用于编辑模式
    if (this.initialData) {
      this.originalData = JSON.parse(JSON.stringify(this.initialData)); // 深拷贝保存原始数据
      this.initFormData(this.initialData);
    }
    
    // 加载可用房间列表
    this.getAvailableRooms();
  },
  methods: {
    // 获取可用房间列表
    getAvailableRooms() {
      const params = { ...this.roomQueryParams };
      if (this.roomSearchName) {
        params.name = this.roomSearchName;
      }

      listAvailableRooms(params).then(response => {
        if (response.code === 200) {
          this.roomList = response.rows || [];
        } else {
          this.$modal.msgError(response.msg || "获取房间列表失败");
          this.roomList = [];
        }
      }).catch(error => {
        console.error("获取可用房间列表失败:", error);
        this.$modal.msgError("获取房间列表失败");
      });
    },

    // 搜索房间
    handleSearchRoom() {
      this.roomQueryParams.pageNum = 1;
      this.getAvailableRooms();
    },
    
    // 初始化表单数据（编辑模式）
    initFormData(data) {
      this.preRegisterForm.registerId = data.registerId;
      this.preRegisterForm.remark = data.remark || '';
      
      // 处理主租户信息
      if (data.mainRenter) {
        this.preRegisterForm.mainRenter = { ...data.mainRenter };
      }
      
      // 处理同住人列表
      this.preRegisterForm.cohabitants = [];
      if (data.renterList && data.renterList.length > 0) {
        // 筛选出非主申请人的同住人
        const cohabitants = data.renterList.filter(renter => renter.mainFlag === '2');
        if (cohabitants.length > 0) {
          this.preRegisterForm.cohabitants = cohabitants.map(renter => ({
            name: renter.name,
            contacts: renter.contacts,
            idCardNumber: renter.idCardNumber,
            picUrl: renter.picUrl,
            mainFlag: '2', // 标记为同住人
            registerRenterId: renter.registerRenterId, // 保留原来的ID用于更新
            renterType: renter.renterType
          }));
        }
      }
      
      // 设置房间ID
      if (data.roomId) {
        this.preRegisterForm.roomId = data.roomId && data.roomId > 0 ? data.roomId : null;
      }
    },
    
    // 添加同住人
    addCohabitant() {
      this.preRegisterForm.cohabitants.push({
        name: '',
        contacts: '',
        idCardNumber: '',
        picUrl: '',
        mainFlag: '2', // 标记为同住人
        renterType: '1' // 默认省内房客
      });
    },
    
    // 移除同住人
    removeCohabitant(index) {
      this.preRegisterForm.cohabitants.splice(index, 1);
    },
    
    // 上传前校验
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    
    // 上传成功回调
    handleUploadSuccess(res, index) {
      if (res.code === 200) {
        if (index === 'main') {
          this.preRegisterForm.mainRenter.picUrl = res.url || res.data;
        } else {
          this.preRegisterForm.cohabitants[index].picUrl = res.url || res.data;
        }
      } else {
        this.$message.error('上传失败: ' + (res.msg || '未知错误'));
      }
    },
    
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 构造提交数据
          const formData = this.formatSubmitData();
          // 触发父组件的提交事件
          this.$emit('submit', formData);
        } else {
          return false;
        }
      });
    },
    
    // 格式化提交数据
    formatSubmitData() {
      // 构造提交的数据结构
      const submitData = {
        registerId: this.preRegisterForm.registerId,
        remark: this.preRegisterForm.remark,
        mainRenter: { ...this.preRegisterForm.mainRenter },
        renterList: [
          { ...this.preRegisterForm.mainRenter } // 主申请人
        ],
        roomId: this.preRegisterForm.roomId // 添加房间ID
      };
      
      // 添加同住人列表
      if (this.preRegisterForm.cohabitants.length > 0) {
        submitData.renterList = [
          ...submitData.renterList,
          ...this.preRegisterForm.cohabitants
        ];
      }
      
      return submitData;
    },
    
    // 取消操作
    cancel() {
      // 如果有原始数据，恢复表单到原始状态
      if (this.originalData) {
        this.initFormData(this.originalData);
      }
      this.$emit('cancel');
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.cohabitant-item {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 20px;
}
.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style> 